package com.java.crazy.part17.net;

import com.java.crazy.base.BaseClass;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class ServerThread extends BaseClass implements Runnable {
    private Socket socket = null;
    private BufferedReader bufferedReader = null;

    public ServerThread(Socket socket) throws IOException {
        this.socket = socket;
        bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    @Override
    public void run() {
        try {
            String msg = null;
            logi("msg:" + msg);
            while ((msg = ReadFromClient()) != null) {
                logi("msg:" + msg);
                for (Socket s : MyServer.socketList) {
                    PrintStream printStream = new PrintStream(s.getOutputStream());
                    printStream.print("aaaaa：" + msg);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private String ReadFromClient() {
        try {
            String content = bufferedReader.readLine();
            logi("content:" + content);
            return content;
        } catch (IOException e) {
            e.printStackTrace();
            MyServer.socketList.remove(socket);
        }
        return null;
    }
}
